package com.zzedu.web.controller.system;

import com.zzedu.common.core.domain.Ztree;
import com.zzedu.system.domain.SysRegion;
import com.zzedu.system.service.ISysRegionService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/system/region")
public class SysRegionController {
    private String prefix = "system/region";

    @Autowired
    private ISysRegionService sysRegionService;

    /**
     * 选择区域
     */
    @GetMapping("/tree/{id}")
    public String tree(@PathVariable("id") Long id, ModelMap modelMap) {
        modelMap.put("loadUrl", "/regionTreeData/" + id);
        return prefix + "/tree";
    }

    /**
     * 加载区域
     */
    @GetMapping("/regionTreeData/{id}")
    @ResponseBody
    public List<Ztree> regionTreeData(@PathVariable("id") Long id) {
        List<Ztree> ztrees = Optional.ofNullable(sysRegionService.list(Wrappers.lambdaQuery(SysRegion.class).in(SysRegion::getRegionLevel, 0, 1, 2)
        )).orElse(Lists.newArrayList()).stream().map(region -> {
            Ztree ztree = new Ztree();
            ztree.setName(region.getRegionName());
            ztree.setId(Long.valueOf(region.getRegionId()));
            ztree.setpId(Long.valueOf(region.getParentId()));
            ztree.setTitle(region.getRegionName());
            return ztree;
        }).collect(Collectors.toList());
        return ztrees;
    }

    /**
     * 加载区域
     */
    @GetMapping("/queryRegion")
    @ResponseBody
    public List<SysRegion> queryRegion(Long province, Long city, Long area) {
        Long id = null;
        if (null != province) {
            id = province;
        }
        if (null != city) {
            id = city;
        }
        if (null != area) {
            id = area;
        }
        List<SysRegion> sysRegionList = Lists.newArrayList();
        if (null == id) {
            sysRegionList = sysRegionService.list(Wrappers.lambdaQuery(SysRegion.class).in(SysRegion::getRegionLevel, 1));
        } else {
            sysRegionList = sysRegionService.list(Wrappers.lambdaQuery(SysRegion.class).in(SysRegion::getParentId, id));
        }
        return sysRegionList;
    }
}
